package com.struts.config;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class StrutsConfig {

	public static Map<String, XmlBean> getStrutsConfig(String filePath)throws Exception{
		
		Map<String, XmlBean> xmlMap = new HashMap<String, XmlBean>();
		
		Document doc = new SAXReader().read(new File(filePath));
		
		Element root = doc.getRootElement();
		
		Element actionroot = root.element("action-mapping");
		List<Element> actions = actionroot.elements();
		
		String path = null;
		
		for(Element a : actions){
			
			XmlBean xmlBean = new XmlBean();
			
			String name = a.attributeValue("name");
			xmlBean.setBeanName(name);
			
			path = a.attributeValue("path");
			xmlBean.setPath(path);
			
			String actionClass = a.attributeValue("type");
			xmlBean.setActionClass(actionClass);
			
			List<Element> forwards = a.elements();
			
			Map<String, String> map = new HashMap<String, String>();
			
			for(Element f : forwards){
				
				String fname = f.attributeValue("name");
				String fvalue = f.attributeValue("value");
				map.put(fname, fvalue);
			}
			
			xmlBean.setActionForward(map);
			
			Element beanroot = root.element("beans");
			List<Element> beans = beanroot.elements();
			
			for(Element b : beans){
				
				if(name.equals(b.attributeValue("name"))){
					
					String beanClass = b.attributeValue("class");
					xmlBean.setBeanClass(beanClass);
					break;
				}
			}
			
			xmlMap.put(path, xmlBean);
		}
		
		return xmlMap;
	}
	
}
